#pragma once
#include <aaudio/AAudio.h>
#include <android/log.h>
#include <fcntl.h>
#include <libavutil/log.h>
#include <unistd.h>

#include <map>
#include <mutex>
#include <queue>
#include <string>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavutil/imgutils.h>
#include <libavutil/rational.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
#include <unistd.h>
}
namespace codec {
class Parse {
 public:
  bool open();
  void close();
  AVPacket* readNextPacket();
  AVCodecParameters* getVideoCodecParams() const;
  AVCodecParameters* getAudioCodecParams() const;
  AVRational getVideoTimeBase() const;
  AVRational getAudioTimeBase() const;
  int getVideoStreamIndex() const { return video_stream_index_; }
  int getAudioStreamIndex() const { return audio_stream_index_; }
  double getDuration() const {
    int64_t duration_us = format_ctx_->duration;
    double duration_sec = static_cast<double>(duration_us) / AV_TIME_BASE;
    return duration_sec;
  }
  std::map<std::string, std::string> getMessage() {
    auto result = std::map<std::string, std::string>();
    result["duration"] = std::to_string(getDuration());
    result["height"] = std::to_string(getVideoCodecParams()->height);
    result["width"] = std::to_string(getVideoCodecParams()->width);
    return result;
  }
  void setDataSource(int fd) { fd_ = fd; }
  bool SeekTo(int64_t timestamp_ms) {
    if (!format_ctx_) return false;

    // 毫秒→微秒 (直接转换)
    const int64_t target_ts = av_rescale(timestamp_ms, AV_TIME_BASE, 1000);
    if (target_ts < 0 || target_ts > format_ctx_->duration) return false;
    __android_log_print(ANDROID_LOG_ERROR, "fhq", "target_ts %zu", target_ts);
    std::lock_guard<std::mutex> lock(seek_mutex_);

    // 设置50ms容错范围
    const int64_t tolerance = av_rescale(50, AV_TIME_BASE, 1000);

    int ret = avformat_seek_file(format_ctx_,
                                 -1,                     // 所有流
                                 0,                      // 最小时间
                                 target_ts,              // 目标时间
                                 target_ts,              // 最大时间
                                 AVSEEK_FLAG_BACKWARD);  // 允许非关键帧

    // 错误处理
    if (ret < 0) {
      char errbuf[256];
      av_strerror(ret, errbuf, sizeof(errbuf));
      __android_log_print(ANDROID_LOG_ERROR, "fhq", "parse SeekTo %s", errbuf);
    }
    return ret >= 0;
  }

 private:
  int fd_;
  std::mutex seek_mutex_;
  AVIOContext* avio_ctx_ = nullptr;
  AVFormatContext* format_ctx_ = nullptr;
  int video_stream_index_ = -1;
  int audio_stream_index_ = -1;
  static int read_packet(void* opaque, uint8_t* buf, int buf_size);
  static int64_t seek_packet(void* opaque, int64_t offset, int whence);
};
};  // namespace codec